<?php
require 'TVB/pms/pdes/common/bootstrap.php';

$company_code  = isset($_REQUEST['company_code']) ? $_REQUEST['company_code'] : null;
if (is_null($company_code))
{
	$status = 500;
	$status_text = 'Company Code is null !';
	$cpl_data = array();
}
$cpl_id  = isset($_REQUEST['cpl_id']) ? $_REQUEST['cpl_id'] : null;
if (is_null($cpl_id) || $cpl_id == 0)
{
	$status = 501;
	$status_text = 'Programme No. is null !';
	$cpl_data = array();
}

$xml = new xml();
//only one func for now
$func_code = array(3);

foreach($func_code as $code)
{
	if ($company_code && $cpl_id)
	{
		$url = AC::MAM_API_URL."FUNCT_CODE=".$code."&CO_CODE=".$company_code."&PGM_NUM=".$cpl_id;
		$ret = CommonUtils::curl_test($url, array());

		$out = $xml->parse($ret, NULL);
		if ($code == 3)
		{
			if (!isset($out['Programmes']['ERROR']))
			{
				if (isset($out['Programmes']))
				{
					$cpl_data['title'] = !preg_match('/^{{[0-9]+}}$/', trim($out['Programmes']['Programme']['CHINESE_TITLE'])) ? trim($out['Programmes']['Programme']['CHINESE_TITLE']) : '';
					$cpl_data['title_en'] = !preg_match('/^{{[0-9]+}}$/', trim($out['Programmes']['Programme']['TITLE'])) ? trim($out['Programmes']['Programme']['TITLE']) : '';
					//$cpl_data['episode_no'] = $out['Programmes']['Programme']['NUM_OF_EPI'];
					$cat_code = $out['Programmes']['Programme']['CAT_CODE'];
					$cat_sub_code = $out['Programmes']['Programme']['CAT_SUB_CODE'];
					$cpl_data['cpl_category_id'] = cpl_category::getCplCategoryID(trim($cat_code), trim($cat_sub_code));
					$status = 200;
					$status_text = 'OK';
				}
				else
				{
					$status = 505;
					$status_text = 'curl data is null';
					$cpl_data = array();
				}
			}
			else
			{
				$status = 505;
				$status_text = 'curl data is null';
				$cpl_data = array();
			}
		}
		elseif ($code == 10)
		{
			if (isset($out['Castings']))
			{
				foreach ($out['Castings']['Casting'] as $cast)
				{
					$cpl_data['casts'][] = $cast;
				}
			}
		}
	}
}

$result = array (
	'status' => $status,
	'status_text' => $status_text,
	'data' => $cpl_data
);

echo json_encode($result);
?>
